<template>
  <div class="signature-pad">
    <el-button @click="handleOrientationChange">切换</el-button>
    <el-button type="primary" @click="onClear">清空</el-button>
    <el-button type="primary" @click="onUndo">撤销</el-button>
    <el-button type="primary" @click="onGetPNG">生成PNG</el-button>
    <canvas ref="canvas"></canvas>
    <img :class="['signature_img', toggleRotate ? 'signature_img_rotate' : '']" v-if="imgSrc" :src="imgSrc" />
  </div>
</template>

<script>
import SmoothSignature from 'smooth-signature';

export default {
  name: 'SignaturePad',
  props: {
    width: {
      type: Number,
      default: () => window.innerWidth,
    },
    height: {
      type: Number,
      default: () => window.innerHeight,
    },
  },
  data() {
    return {
      signaturePad: null,
      toggleRotate: false,
      options: {
        // 设置宽度和高度，根据横竖屏切换调整
        width: this.width - 20,
        height: this.height - 30,
        scale: 2,
        minWidth: 4,
        maxWidth: 10,
        color: '#1890ff',
        // bgColor: '#efefef'
      },
      imgSrc: null
    };
  },
  mounted() {
    let el = this.$refs.canvas;
    this.options.width = this.width - 20;
    this.options.height = this.height - 30;
    this.initSignaturePad(el, this.options);
  },
  beforeUnmount() {
  },
  methods: {
    // 初始化签名板
    initSignaturePad(el, options) {
      this.signaturePad = new SmoothSignature(el, options);
    },
    /**
     * 撤销
     */
    onUndo() {
      this.signaturePad.undo();
    },
    /**
     * 清空
     */
    onClear() {
      this.signaturePad.clear();
    },
    onGetPNG() {
      const isEmpty = this.signaturePad.isEmpty();
      if (isEmpty) {
        console.log('签名为空，无法生成图片');
        return;
      }
      let png = this.signaturePad.getPNG();
      this.imgSrc = png;
      console.log(png);
    },
    handleOrientationChange() {
      this.toggleRotate = !this.toggleRotate;
      if (this.toggleRotate) {
        this.options.width = 300;
        this.options.height = 500;
      } else {
        this.options.width = this.width - 20;
        this.options.height = this.height - 30;
      }
      let el = this.$refs.canvas;
      this.signaturePad = new SmoothSignature(el, this.options);
      this.signaturePad.getRotateCanvas(-90)
    },
  },
};
</script>

<style scoped>
.signature-pad {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.signature_img {
  position: absolute;
  top: 10px;
  right: 20px;
  width: 500px;
  height: 300px;
  border: 1px solid #ccc;
}

.signature_img_rotate {
  width: 300px;
  height: 500px;
  transform: rotate(-90deg);
}
</style>